package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@ControllerAdvice//@RestControllerAdvice=@ControllerAdvice+@ResponseBody
public class GlobalExceptionHandler {//todo 抛出的异常信息名一定是errMessage,前端规定了,底层是基于AOP
//不搭配 @ResponseBody 的 @ControllerAdvice,return "error"; // 返回视图名称，由视图解析器解析为页面
    @ResponseBody
    @ExceptionHandler(XueChengPlusException.class)//捕获自定义异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码500,默认Internal Server Error
    public RestErrorResponse customException(XueChengPlusException e) {
        log.error("【系统异常】{}",e.getErrMessage(),e);
        return new RestErrorResponse(e.getErrMessage());

    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)//捕获JR303异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码500,默认Internal Server Error
    public RestErrorResponse jr303Exception(MethodArgumentNotValidException e) {// todo jsr303还可以手写校验giuz
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        ArrayList<String> errors = new ArrayList<>();
        fieldErrors.stream().forEach(item ->{
            errors.add(item.getDefaultMessage());
        });
        String join = StringUtils.join(errors, ",");
//        不能直接e.getMessage()获取jr3030的报错信息,这样前端难以接收 todo  hsp在springBoot家具 框架中也讲过
        log.error("【系统异常】{}",join);
        return new RestErrorResponse(join);

    }

    @ResponseBody
    @ExceptionHandler(Exception.class)//捕获其他异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e) {
        log.error("【系统异常】{}",e.getMessage(),e);
        if(e.getMessage().equals("不允许访问")){
            return new RestErrorResponse("没有操作此功能的权限");
        }
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());

    }
}
